﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GdHotel.Data.Helpers;

namespace GdHotel.Data.Templates
{
    public class TemplateBuilder
    {
        public String Template { get; private set; }
        private List<Tuple<String, String>> Replacements { get; set; }

        public TemplateBuilder(String template)
        {
            Template = template;
            Replacements = new List<Tuple<String, String>>();
        }

        public TemplateBuilder AppendReplacement(String pattern, String replacement)
        {
            Replacements.Add(new Tuple<String, String>(pattern, replacement));
            return this;
        }

        public TemplateBuilder AppendReplacement(String pattern, Object value)
        {
            if (value is Boolean)
                return AppendReplacement(pattern, (Boolean) value);
            if (value is DateTime)
                return AppendReplacement(pattern, (DateTime)value);
            if (value == null)
                return AppendReplacement(pattern, "");

            var replacement = value.ToString();
            return AppendReplacement(pattern, replacement);
        }

        public TemplateBuilder AppendReplacement(String pattern, Boolean value)
        {
            var replacement = value ? "+" : "-";
            return AppendReplacement(pattern, replacement);
        }

        public TemplateBuilder AppendReplacement(String pattern, DateTime value)
        {
            string replacement;
            if (value.TimeOfDay.Equals(new TimeSpan(0)))
                replacement = value.ToString("dd.MM.yyyy");
            else
                replacement = value.ToString();
            return AppendReplacement(pattern, replacement);
        }

        public String Build()
        {
            var result = new StringBuilder(Template);
            for (int i = 0; i < Replacements.Count; i++)
                result = result.Replace("[%{0}%]".F(Replacements[i].Item1), Replacements[i].Item2);
            return result.ToString();
        }
    }
}
